package com.encrypt;

import com.encrypt.util.ByteToString;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by huangyugen on 2019/04/28
 * 结合了MD5和SHA算法的优势，并且加入了密钥的支持
 **/
public class MacCoder {

    public final static String HmacMD5 = "HmacMD5";
    public final static String HmacSHA1 = "HmacSHA1";
    public final static String HmacSHA256 = "HmacSHA256";
    public final static String HmacSHA384 = "HmacSHA384";
    public final static String HmacSHA512 = "HmacSHA512";

    public static byte[] initHmacMd5key(String macType)throws Exception{
        KeyGenerator hmacMD5 = KeyGenerator.getInstance(macType);
        //产生密钥
        SecretKey secretKey = hmacMD5.generateKey();
        //获得密钥
        return secretKey.getEncoded();
    }

    public static String encodeHmac(byte[] data,byte[] key,String macType)throws Exception{
        //还原密钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, macType);
        //实例化mac
        Mac instance = Mac.getInstance(secretKeySpec.getAlgorithm());
        //初始化Mac
        instance.init(secretKeySpec);
        //执行消息摘要
        return ByteToString.byteArrayToHexString(instance.doFinal(data));
    }

    public static void main(String[] args) throws Exception{
        String data = "Java加密与解密的艺术";
        System.out.println("【原 文】："+data);
        System.out.println("【编码后】："+HmacMD5+"      --> "+MacCoder.encodeHmac(data.getBytes(),MacCoder.initHmacMd5key(HmacMD5),HmacMD5));
        System.out.println("【编码后】："+HmacSHA1+"     --> "+MacCoder.encodeHmac(data.getBytes(),MacCoder.initHmacMd5key(HmacSHA1),HmacSHA1));
        System.out.println("【编码后】："+HmacSHA256+"   --> "+MacCoder.encodeHmac(data.getBytes(),MacCoder.initHmacMd5key(HmacSHA256),HmacSHA256));
        System.out.println("【编码后】："+HmacSHA384+"   --> "+MacCoder.encodeHmac(data.getBytes(),MacCoder.initHmacMd5key(HmacSHA384),HmacSHA384));
        System.out.println("【编码后】："+HmacSHA512+"   --> "+MacCoder.encodeHmac(data.getBytes(),MacCoder.initHmacMd5key(HmacSHA512),HmacSHA512));
    }

}
